<template>
    <div class="notice-manager">
        <!-- 页面标题区域 -->
        <div class="page-header">
            <h2>通知管理</h2>
            <el-tag type="info">共 {{ total }} 条通知</el-tag>
        </div>

        <div class="content-box">
            <!-- 操作栏 -->
            <el-card class="operation-area" shadow="hover">
                <!-- 搜索区域 -->
                <el-form ref="searchFormRef" :inline="true" :model="listQuery" class="search-form">
                    <el-form-item label="通知标题">
                        <el-input v-model="listQuery.title" placeholder="请输入标题" clearable></el-input>
                    </el-form-item>
   
                    <el-form-item>
                        <el-button size="default" type="primary" plain @click="onSubmit">
                            <el-icon><Search /></el-icon> 查询
                        </el-button>
                        <el-button size="default" plain @click="onReset">
                            <el-icon><Refresh /></el-icon> 重置
                        </el-button>
                    </el-form-item>
                </el-form>

                <!-- 按钮区域 -->
                <div class="control-btns">
                    <el-button type="danger" plain size="default" @click="batchDelete" :disabled="!multipleSelection.length">
                        <el-icon><Delete /></el-icon> 批量删除
                    </el-button>
                    <div class="right-btns">
                        <el-button type="primary" plain size="default" @click="openDialog()">
                            <el-icon><Plus /></el-icon> 发布通知
                        </el-button>
                    </div>
                </div>
            </el-card>

            <!-- 表格区域 -->
            <el-card class="table-card" shadow="hover">
                <el-table ref="multipleTableRef"
                         v-loading="listLoading" 
                         :data="tableData" 
                         tooltip-effect="dark" 
                         style="width: 100%" 
                         size="default"
                         @selection-change="handleSelectionChange"
                         border>
                    <el-table-column type="selection" width="50" align="center"></el-table-column>
                    <el-table-column prop="id" label="编号" width="80" align="center"></el-table-column>
                    <el-table-column prop="title" label="标题" min-width="150"></el-table-column>
                    <el-table-column label="标签" width="200">
                        <template #default="scope">
                            <span>{{ formatTags(scope.row.tags) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="time" label="发布时间" width="160" align="center"></el-table-column>
                    <el-table-column label="操作" width="180" align="center" fixed="right">
                        <template #default="scope">
                            <el-button size="small" type="primary" plain @click="openDialog(scope.row)">
                                <el-icon><Edit /></el-icon> 编辑
                            </el-button>
                            <el-button size="small" type="danger" plain @click="handleDelete(scope.$index, scope.row)">
                                <el-icon><Delete /></el-icon> 删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <pagination v-show="total > 0" 
                          :total="total" 
                          v-model:page="listQuery.currentPage"
                          v-model:limit="listQuery.pageSize"
                          @pagination="fetchData" />
            </el-card>

            <!-- 新增/编辑弹窗 -->
            <el-dialog :title="dialogForm.id ? '编辑通知' : '发布通知'" 
                      v-model="formVisible"
                      width="500px"
                      :close-on-click-modal="false">
                <el-form :model="dialogForm" :rules="formRules" ref="dialogFormRef" label-width="100px">
                    <el-form-item label="通知标题" prop="title">
                        <el-input v-model="dialogForm.title" placeholder="请输入通知标题"></el-input>
                    </el-form-item>
                    <el-form-item label="通知内容" prop="content">
                        <el-input type="textarea" 
                                 v-model="dialogForm.content" 
                                 :autosize="{ minRows: 4, maxRows: 8 }" 
                                 placeholder="请输入通知内容"
                                 maxlength="500"
                                 show-word-limit>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="标签" prop="tags">
                        <div class="tags-input-container">
                            <el-tag v-for="tag in dialogForm.tags"
                                   :key="tag"
                                   closable
                                   @close="removeFormTag(tag)"
                                   style="margin-right: 6px; margin-bottom: 6px">
                                {{tag}}
                            </el-tag>
                            <el-input v-if="dialogForm.tags.length < 3"
                                     v-model="dialogForm.tagInputValue"
                                     size="small"
                                     style="width: 100px"
                                     @keyup.enter="handleFormTagInput"
                                     @blur="handleFormTagInput"
                                     placeholder="+ 添加标签">
                            </el-input>
                        </div>
                        <div class="tags-tip" style="font-size: 12px; color: #909399; margin-top: 5px">
                            最多添加3个标签，按回车或失去焦点时添加
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="formVisible = false" plain>取 消</el-button>
                        <el-button type="primary" :loading="isSubmit" @click="handleSave" plain>确 定</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElCard, ElForm, ElFormItem, ElInput, ElTag, ElButton, ElTable, ElTableColumn, ElDialog, ElIcon } from 'element-plus'
import { Search, Refresh, Delete, Plus, Edit } from '@element-plus/icons-vue'
import Pagination from '../components/Pagination/index.vue'
import Request from '../utils/request.js'

// 表单引用
const searchFormRef = ref()
const multipleTableRef = ref()
const dialogFormRef = ref()

// 响应式数据
const urlPrefix = '/notice/' // URL 前缀
const pageTitle = '通知'

const listLoading = ref(true)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const formVisible = ref(false)
const isSubmit = ref(false)

const listQuery = reactive({
    title: '',
    tags: [],
    tagInputValue: '',
    currentPage: 1,
    pageSize: 10
})

const dialogForm = reactive({
    id: undefined,
    title: '',
    content: '',
    tags: [],
    tagInputValue: ''
})

const tagOptions = ['重要', '紧急', '普通', '公告']

const formRules = reactive({
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
    tags: [{ required: true, message: '请至少添加一个标签', trigger: 'change' }]
})

// 处理选择变化
const handleSelectionChange = (val) => {
    multipleSelection.value = val.map(v => v.id)
}

// 打开对话框
const openDialog = (row = {}) => {
    // 确保 tags 是数组
    const tags = row.tags ? (Array.isArray(row.tags) ? row.tags : row.tags.split(',').filter(Boolean)) : [];

    Object.assign(dialogForm, {
        ...row,
        tagInputValue: '',
        tags: tags
    });
    formVisible.value = true;
}

// 处理删除
const handleDelete = (index, row) => {
    ElMessageBox.confirm('此操作将删除选中数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        Request.delete(urlPrefix + row.id).then(response => {
            if (response.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功!'
                })
                onReset()
            } else {
                ElMessage({
                    type: 'error',
                    message: response.msg
                })
            }
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

// 批量删除
const batchDelete = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            message: '请先选择要删除的数据！',
            type: 'warning'
        })
    } else {
        Request.delete(`${urlPrefix}deleteBatch?ids=${multipleSelection.value.join(',')}`).then(res => {
            if (res.code === '0') {
                ElMessage({
                    showClose: true,
                    message: '批量删除成功',
                    type: 'success'
                });
                onReset()
            } else {
                ElMessage({
                    showClose: true,
                    message: res.msg,
                    type: 'error',
                });
            }
        })
    }
}

// 获取数据
const fetchData = () => {
    listLoading.value = true
    Request.get(`${urlPrefix}page`, {
        params: {
            title: listQuery.title,
            tags: listQuery.tags.join(','),
            currentPage: listQuery.currentPage,
            size: listQuery.pageSize,
        }
    }).then(response => {
        const data = response.data;
        if (response.code === '0') {
            total.value = data.total
            tableData.value = data.records.map(record => ({
                ...record,
                tags: record.tags ? record.tags.split(',').filter(Boolean) : []
            }));
        }
    })
    listLoading.value = false
}

// 提交搜索
const onSubmit = () => {
    listQuery.currentPage = 1
    fetchData()
}

// 重置搜索
const onReset = () => {
    listQuery.currentPage = 1
    listQuery.pageSize = 10;
    listQuery.title = '';
    listQuery.tags = [];
    listQuery.tagInputValue = '';
    fetchData()
}

// 保存表单
const handleSave = () => {
    dialogFormRef.value.validate(valid => {
        if (valid) {
            const formData = {
                ...dialogForm,
                tags: dialogForm.tags.join(',')
            };
            const requestMethod = formData.id ? Request.put : Request.post;
            const url = formData.id ? `${urlPrefix}${formData.id}` : "/notice";
            isSubmit.value = true;
            requestMethod(url, formData).then(response => {
                isSubmit.value = false;
                if (response.code == 0) {
                    ElMessage({
                        showClose: true,
                        message: formData.id ? '更新成功' : '添加成功',
                        type: 'success',
                    });
                    fetchData()
                    formVisible.value = false
                } else {
                    ElMessage({
                        showClose: true,
                        message: response.msg,
                        type: 'error',
                    });
                }
            }).catch(() => {
                isSubmit.value = false;
            });
        }
    });
}

// 格式化标签
const formatTags = (tags) => {
    if (!tags || !Array.isArray(tags)) return '';
    return tags.slice(0, 3).join('，');
}

// 处理搜索标签输入
const handleSearchTagInput = () => {
    const tagValue = listQuery.tagInputValue.trim();
    if (tagValue) {
        if (listQuery.tags.length >= 3) {
            ElMessage({
                message: '最多只能添加3个标签',
                type: 'warning'
            });
            return;
        }
        if (!listQuery.tags.includes(tagValue)) {
            listQuery.tags.push(tagValue);
        }
        listQuery.tagInputValue = '';
    }
}

// 移除搜索标签
const removeSearchTag = (tag) => {
    const index = listQuery.tags.indexOf(tag);
    if (index > -1) {
        listQuery.tags.splice(index, 1);
    }
}

// 处理表单标签输入
const handleFormTagInput = () => {
    const tagValue = dialogForm.tagInputValue.trim();
    if (tagValue) {
        if (dialogForm.tags.length >= 3) {
            ElMessage({
                message: '最多只能添加3个标签',
                type: 'warning'
            });
            return;
        }
        if (!dialogForm.tags.includes(tagValue)) {
            dialogForm.tags.push(tagValue);
        }
        dialogForm.tagInputValue = '';
    }
}

// 移除表单标签
const removeFormTag = (tag) => {
    const index = dialogForm.tags.indexOf(tag);
    if (index > -1) {
        dialogForm.tags.splice(index, 1);
    }
}

// 生命周期钩子
onMounted(() => {
    fetchData()
})
</script>

<style lang="less" scoped>
.notice-manager {
    padding: 24px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
}

.page-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;

    h2 {
        font-size: 24px;
        font-weight: 500;
        color: #1f2f3d;
        margin: 0;
        margin-right: 15px;
    }
}

.operation-area {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
}

.search-form {
    margin-bottom: 20px;
    padding: 20px 20px 0;
    background-color: #fafafa;
    border-radius: 4px;
}

.table-card {
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.control-btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px 20px;

    .right-btns {
        display: flex;
        gap: 10px;
    }
}

:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: none;

    th {
        background-color: #fafafa;
        font-weight: 500;
        color: #1f2f3d;
        padding: 12px 0;
    }

    td {
        padding: 12px 0;
    }
}

:deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    .el-dialog__header {
        padding: 24px;
        border-bottom: 1px solid #ebeef5;
        margin: 0;
    }

    .el-dialog__title {
        font-size: 18px;
        font-weight: 500;
        color: #1f2f3d;
    }

    .el-dialog__body {
        padding: 32px 24px;
    }

    .el-dialog__footer {
        padding: 16px 24px;
        border-top: 1px solid #ebeef5;
    }
}
</style>